
package cn.airnan.dg.controller;

import cn.airnan.dg.configs.Global;
import cn.airnan.dg.entity.Player;
import cn.airnan.dg.entity.Room;
import cn.airnan.dg.service.RoomService;
import cn.airnan.dg.utils.CommonResponse;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;


/**
 * 房间相关接口
 */
@RestController
@RequestMapping("/api/room")
public class RoomController {

    private static final Logger log = LoggerFactory.getLogger(RoomController.class);
    @Resource
    private RoomService service;

    /**
     * 获取房间列表
     *
     * @return 房间列表
     */
    @GetMapping("/list")
    public CommonResponse list() {
        try {
            return CommonResponse.success(service.getRooms());
        } catch (Exception e) {
            return CommonResponse.error(e.getMessage());
        }
    }

    /**
     * 创建房间
     *
     * @return 房间信息
     */
    @PostMapping("/create")
    public CommonResponse create(@RequestBody Room room) {
        try {
            if (service.canCreateRoom(room.getId())) {
                var result = service.createRoom(room);
                if (result != null) {
                    log.info("【创建房间】{}创建房间:{}", room.getMaster(), room.getId());
                    return CommonResponse.success(result);
                } else {
                    return CommonResponse.error("创建房间失败，请重试！");
                }
            } else {
                return CommonResponse.error("房间名已存在，换一个吧！");
            }
        } catch (Exception e) {
            return CommonResponse.error(e.getMessage());
        }
    }

    /**
     * 判断是否可以加入房间
     *
     * @return true/false
     */
    @PostMapping("/canJoin")
    public CommonResponse canJoin(@RequestBody Room room) {
        try {
            if (service.canJoinRoom(room.getId())) {
                List<Player> players = Global.ROOMS.get(room.getId()).getPlayers();
                for (Player player : players) {
                    if (Objects.equals(room.getPlayers().getFirst().getId(), player.getId())) {
                        return CommonResponse.error("已经在房间里了！");
                    }
                }
                return CommonResponse.success(true);
            } else {
                return CommonResponse.error("房间已满或已经开始游戏，再换一个吧！");
            }
        } catch (Exception e) {
            return CommonResponse.error(e.getMessage());
        }
    }

}
